package com.guagua.system.controller;

import com.guagua.common.response.Result;
import com.guagua.system.dto.LoginDTO;
import com.guagua.system.dto.RegisterDTO;
import com.guagua.system.entity.User;
import com.guagua.system.security.BlogUserDetails;
import com.guagua.system.security.JwtUtils;
import com.guagua.system.security.SecurityUtils;
import com.guagua.system.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Tag(name = "认证管理", description = "认证相关接口")
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
    
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final AuthenticationManager authenticationManager;
    private final JwtUtils jwtUtils;
    
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<String> login(@Valid @RequestBody LoginDTO loginDTO) {
        try {
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                    loginDTO.getUsername(),
                    loginDTO.getPassword()
                )
            );
            
            String jwt = jwtUtils.generateToken(
                (BlogUserDetails) authentication.getPrincipal()
            );
            return Result.success(jwt);
        } catch (BadCredentialsException e) {
            return Result.error("用户名或密码错误");
        }
    }
    
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<Void> register(@Valid @RequestBody RegisterDTO registerDTO) {
        if (userService.isUsernameExists(registerDTO.getUsername())) {
            return Result.error("用户名已存在");
        }
        
        if (userService.isEmailExists(registerDTO.getEmail())) {
            return Result.error("邮箱已被使用");
        }
        
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setNickname(registerDTO.getNickname());
        user.setEmail(registerDTO.getEmail());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        userService.save(user);
        return Result.success();
    }

    @Operation(summary = "获取当前用户信息")
    @GetMapping("/current")
    public Result<User> getCurrentUser() {
        Long userId = SecurityUtils.getCurrentUserId();
        User user = userService.getById(userId);
        user.setPassword(null); // 不返回密码
        return Result.success(user);
    }
} 